import { Button, Col, Divider, Form, Input, message, Row, Select } from "antd"
import React, { useEffect, useState } from "react"
import useCategories, { CategoryItem } from "../../../hooks/categories"
import { ObjStrKey, Res } from "../../../types/base"
import $http from "../../../utils/require"
import ProductItem, { ProductItemFace } from "../../../components/productItem"

export interface SearchProductItemFace {
    "sold": number,
    "_id": string,
    "name": string,
    "description": string,
    "price": number,
    "category": string,
    "quantity": number,
    "shipping": boolean,
    "createdAt": string,
    "updatedAt": string,
    "__v": number
}

const Search = () => {
    let [categories] = useCategories()
    let [searchList, setSearchList] = useState<SearchProductItemFace[]>([])

    let categoriesMap: ObjStrKey = {};
    (categories as []).forEach((el: CategoryItem) => {
        categoriesMap[el._id] = el.name
    });

    const onfinish = (values: { category: string, search: string }) => {
        $http['getProductsInSearch'](values).then((res: SearchProductItemFace[]) => {
            setSearchList(res)
        }).catch((err: Res) => {
            setSearchList([])
            message.error(err.error)
        })
    }
    return (
        <>
            <Form layout="inline" initialValues={{ category: '' }} onFinish={onfinish}>
                <Input.Group compact>
                    <Form.Item name="category">
                        <Select>
                            <Select.Option value="">所有分类</Select.Option>
                            {

                                (categories as []).map((el: CategoryItem) => {
                                    return <Select.Option value={el._id} key={el._id}>{el.name}</Select.Option>
                                })
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item name="search">
                        <Input placeholder="请输入搜索关键字"></Input>
                    </Form.Item>
                    <Form.Item>
                        <Button htmlType="submit">搜索</Button>
                    </Form.Item>
                </Input.Group>
            </Form>

            <Divider></Divider>

            <Row gutter={[16, 16]}>
                {
                    searchList.map((el: ObjStrKey) => {
                        el.category = categoriesMap[el.category]
                        let item: ProductItemFace = (el as ProductItemFace)
                        return <Col span="6">
                            <ProductItem product={item}></ProductItem>
                        </Col>
                    })
                }

            </Row>
        </>
    )
}

export default Search
